package com.liyuxiang.yygh.user.api;


import com.alibaba.fastjson.JSONObject;
import com.liyuxiang.yygh.common.exception.YyghException;
import com.liyuxiang.yygh.common.helper.JwtHelper;
import com.liyuxiang.yygh.common.result.Result;
import com.liyuxiang.yygh.common.result.ResultCodeEnum;
import com.liyuxiang.yygh.model.user.UserInfo;
import com.liyuxiang.yygh.user.service.UserInfoService;
import com.liyuxiang.yygh.user.utils.ConstantWxPropertiesUtils;
import com.liyuxiang.yygh.user.utils.HttpClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/api/ucenter/wx")
public class WxApiController {
    @Autowired
    private UserInfoService userInfoService;

    //生成微信扫描的二维码
    //生成二维码需要的参数
    @GetMapping("getLoginParam")
    @ResponseBody
    public Result getQrConnect(HttpSession session) {
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("appid", ConstantWxPropertiesUtils.WX_OPEN_APP_ID);
            map.put("scope", "snsapi_login");
            String wxOpenRedirectUrl = ConstantWxPropertiesUtils.WX_OPEN_REDIRECT_URL;
            URLEncoder.encode(wxOpenRedirectUrl, "utf-8");
            map.put("redirectUri", wxOpenRedirectUrl);
            map.put("appid", ConstantWxPropertiesUtils.WX_OPEN_APP_ID);
            map.put("state", System.currentTimeMillis());
            return Result.ok(map);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }

    //扫码之后的回调
    @GetMapping("callback")
    public String callback(String code, String sate) {
        System.out.println("微信授权登录回调");
        System.out.println("code:" + code);
        //用appid、secret、code换用户openid和access_token
        StringBuffer baseAccessTokenUrl = new StringBuffer().append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");
        String accessTokenUrl = String.format(baseAccessTokenUrl.toString(),
                ConstantWxPropertiesUtils.WX_OPEN_APP_ID,
                ConstantWxPropertiesUtils.WX_OPEN_APP_SECRET,
                code);
        try {
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
            System.out.println("accessTokenInfo:" + accessTokenInfo);
            JSONObject jsonObject = JSONObject.parseObject(accessTokenInfo);
            String access_token = jsonObject.getString("access_token");
            String openid = jsonObject.getString("openid");
            //根据openid查询用户是否存在
            UserInfo userInfo = userInfoService.selectWxUserInfoByOpenId(openid);
            if (ObjectUtils.isEmpty(userInfo)) {
                //用户不存在 ，用access_token和openid换用户微信信息
                StringBuffer baseUserInfoUrl = new StringBuffer().append("https://api.weixin.qq.com/sns/userinfo")
                        .append("?access_token=%s")
                        .append("&openid=%s")
                        .append("&lang=zh_CN");
                String userInfoUrl = String.format(baseUserInfoUrl.toString(),
                        access_token,
                        openid,
                        code);
                String userInfoJson = HttpClientUtils.get(userInfoUrl);
                System.out.println("userInfo:" + userInfoJson);
                JSONObject userInfoObj = JSONObject.parseObject(userInfoJson);
                String nickname = userInfoObj.getString("nickname");
                String headimgurl = userInfoObj.getString("headimgurl");
                userInfo = new UserInfo();
                userInfo.setNickName(nickname);
                userInfo.setOpenid(openid);
                userInfo.setStatus(1);
                userInfoService.save(userInfo);
            }
            //判断用户是否被禁用
            if (userInfo.getStatus() == 0) {
                throw new YyghException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
            }
            Map<String, String> map = new HashMap<>();
            String name = userInfo.getName();
            if (StringUtils.isEmpty(name)) {
                name = userInfo.getNickName();
            }
            if (StringUtils.isEmpty(name)) {
                name = userInfo.getPhone();
            }
            if (StringUtils.isEmpty(name)) {
                name = userInfo.getOpenid();
            }
            map.put("name", name);
            if (StringUtils.isEmpty(userInfo.getPhone())) {
                map.put("openid", userInfo.getOpenid());
            } else {
                map.put("openid", "");
            }
            //TODO JWT token生成
            String token = JwtHelper.createToken(userInfo.getId(), name);
            map.put("token", token);
            return "redirect:" + ConstantWxPropertiesUtils.YYGH_BASE_URL + "/weixin/callback?token=" + map.get("token") + "&openid=" + map.get("openid") + "&name=" + URLEncoder.encode(map.get("name"), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
